// pages/TEST/TEST.js
import * as echarts from '../../ec-canvas/echarts';
import {
  scores
} from '../../api/index.js'


var myChart = null
var dateList = ['日', '一', '二', '三', '四', '五', '六']
var scoreList = [0, 0, 0, 0, 0, 0, 0]

function initChart(canvas, width, height) {
  myChart = echarts.init(canvas, null, {
    width: width,
    height: height
  });
  canvas.setChart(myChart);
  var option = {
    color: ['#3398DB'],
    tooltip: {
      trigger: 'axis',
      axisPointer: { // 坐标轴指示器，坐标轴触发有效
        type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '0',
      containLabel: true
    },
    xAxis: [{
      type: 'category',

      data: dateList,
      axisLine: {
        lineStyle: {
          color: '#7AB0FFFF',
        }
      },
      axisTick: {
        alignWithLabel: true,
        // interval: 0,
        // rotate: -30,
        // margin: -15,
        // lineStyle: {
        //   color: '#7AB0FFFF'
        // }
      },
      axisLabel: {
        // interval: 0,
        // rotate: 40,
        color: '#999999',
        textStyle: {
          fontSize: 10 //更改坐标轴文字大小
        }

      },

    }],
    yAxis: [{
      type: 'value',

      axisLine: {
        lineStyle: {
          color: '#7AB0FFFF',
        }
      },
      axisLabel: {
        color: '#999999', //坐标轴文字颜色
        textStyle: {
          fontSize: 10 //更改坐标轴文字大小
        }

      },
    }],
    series: [{
      name: '睡眠分数',
      type: 'bar',
      barWidth: 20,
      itemStyle: {
        normal: {
          //柱形图圆角，初始化效果
          barBorderRadius: [10, 10, 0, 0],
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
            offset: 0,
            color: 'rgba(108,165,255,1)'
          }, {
            offset: 1,
            color: 'rgba(44,108,255,1)'
          }]),
        }
      },
      data: scoreList,
      color: ['#2c6cffFF'],
      background: ['linear-gradient(180deg,rgba(44,108,255,1) 0%,rgba(108,165,255,1) 100%)']
    }]
  };
  myChart.setOption(option);
  console.log('myChart:', myChart)
  return myChart;
}

Page({

  /**
   * 页面的初始数据
   */
  data: {
    index: '2',
    tabs: ["今日", "昨日", "近7日", "近30日"],
    activeIndex: 0,
    sliderOffset: 0,
    sliderLeft: 0,

    ec: {
      onInit: initChart
    },
    //单日分数
    score: 0,
    //单日评价
    evaluation: '',

    //周平均
    week_average_score: 0,
    //周评价
    week_evaluation: '',
    //月均
    month_average_score: 0,
    //月评价
    month_evaluation: '',
    month_img_url: '',
    week_img_url: '',
    //7天的日期
    sevenDates: [],
    //7天分数
    sevenScores: [],
    //月日期
    monthDates: [],
    //月分数
    monthScores: [],
    gradientColor: {
      '0%': '#F2F2F2',
      '100%': '#2C6CFF'
    },

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    this.getMyscores()
  },
  onShow: function() {
  },

  getMyscores() {
    dateList = []
    scoreList = []
    let date = this.getDate()

    scores().then(res => {
      this.setData({
        score: res.scores[0].score == -1 ? '0' : res.scores[0].score
      })

      if (res.errcode == '00000') {
        this.setData({
          evaluation: res.evaluation,
          month_evaluation: res.month_evaluation,
          month_img_url: res.month_normal_status == 1 ? '../../images/qj.png' : (res.month_normal_status == 2 ? '../../images/zc.png' : (res.month_normal_status == 3 ? '../../images/yx.png' : '')),
          month_average_score: res.month_average_score == -1 ? 0 : res.month_average_score,
          week_evaluation: res.week_evaluation,
          week_average_score: res.week_average_score == -1 ? 0 : res.week_average_score,
          week_img_url: res.week_normal_status == 1 ? '../../images/qj.png' : (res.week_normal_status == 2 ? '../../images/zc.png' : (res.week_normal_status == 3 ? '../../images/yx.png' : '')),

        })

        let sevenDays = res.scores.slice(0, 7).reverse()
        let sevenDates = []
        let sevenScores = []
        let monthDates = []
        let monthScores = []
        sevenDays.forEach(item => {
          if (item.score == -1) {
            item.score = 0
          }
          sevenDates.push(item.date)
          sevenScores.push(item.score)
        })

        res.scores.forEach((item) => {
          if (item.score == -1) {
            item.score = 0
          }
          monthDates.push(item.date)
          monthScores.push(item.score)
        })
        this.setData({
          sevenDates: sevenDates,
          sevenScores: sevenScores,
          monthDates: monthDates,
          monthScores: monthScores
        })
        let arrSevenDates = []
        sevenDates.forEach(item => {
          arrSevenDates.push(this.getWeek(item))

        })

        if (this.data.index == 1) {
          dateList = arrSevenDates
          scoreList = sevenScores
        }
        let arrMonthDates = []
        for (let i = 0; i < monthDates.length; i++) {
          arrMonthDates.push('')
        }
        arrMonthDates[0] = monthDates[monthDates.length - 1].split('-')[1] + '/' + monthDates[monthDates.length - 1].split('-')[2]
        arrMonthDates[Math.ceil((monthDates.length - 1) / 2)] = monthDates[Math.ceil((monthDates.length - 1) / 2)].split('-')[1] + '/' + monthDates[Math.ceil((monthDates.length - 1) / 2)].split('-')[2]
        arrMonthDates[monthDates.length - 1] = monthDates[0].split('-')[1] + '/' + monthDates[0].split('-')[2]

        if (this.data.index == 2) {
          dateList = arrMonthDates
          scoreList = monthScores.reverse()
        }



        var option = {
          color: ['#3398DB'],
          tooltip: {
            trigger: 'axis',
            axisPointer: { // 坐标轴指示器，坐标轴触发有效
              type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
            }
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '0',
            containLabel: true
          },
          xAxis: [{
            type: 'category',

            data: dateList,
            axisLine: {
              lineStyle: {
                color: '#7AB0FFFF',
              }
            },
            axisTick: {
              alignWithLabel: true,
              // interval: 0,
              // rotate: -30,
              // margin: -15,
              // lineStyle: {
              //   color: '#7AB0FFFF'
              // }
            },
            axisLabel: {
              // interval: 0,
              // rotate: 40,
              color: '#999999',
              textStyle: {
                fontSize: 10 //更改坐标轴文字大小
              }

            },

          }],
          yAxis: [{
            type: 'value',

            axisLine: {
              lineStyle: {
                color: '#7AB0FFFF',
              }
            },
            axisLabel: {
              color: '#999999', //坐标轴文字颜色
              textStyle: {
                fontSize: 10 //更改坐标轴文字大小
              }

            },
          }],
          series: [{
            name: '睡眠分数',
            type: 'bar',
            barWidth: '28%',
            itemStyle: {
              normal: {
                //柱形图圆角，初始化效果
                barBorderRadius: [10, 10, 0, 0],
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                  offset: 0,
                  color: 'rgba(108,165,255,1)'
                }, {
                  offset: 1,
                  color: 'rgba(44,108,255,1)'
                }]),
              }
            },
            data: scoreList,
            color: ['#2c6cffFF'],
            background: ['linear-gradient(180deg,rgba(44,108,255,1) 0%,rgba(108,165,255,1) 100%)']
          }]
        };

        setTimeout(() => {
          if (myChart) {
            myChart.setOption(option);
          }
        }, 500)


      }





    })

  },


  getDate() {
    let date = new Date();
    date.setTime(date.getTime() - 24 * 60 * 60 * 1000);
    return date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate();
  },

  getWeek(dateString) {
    let dateArray = dateString.split("-");
    let date = new Date(dateArray[0], parseInt(dateArray[1] - 1), dateArray[2]);
    return "日一二三四五六".charAt(date.getDay());
  },
  //分享
  onShareAppMessage: function() {
    return {
      title: '我正在使用SMART睡眠训练计划，超有用！推荐给你',
      imageUrl: '../../images/98875.png'

    }
  },


  tabClick2(e) {
    console.log(e.currentTarget.dataset.index)
    this.setData({
      index: e.currentTarget.dataset.index
    })
    this.getMyscores()
  },
  tabClick: function(e) {
    this.setData({
      sliderOffset: e.currentTarget.offsetLeft,
      activeIndex: e.currentTarget.id
    });
  },
})